package events

import "sync"

type EventBase[T any, M func(...T) | func(T) | func()] struct {
	listener map[*M]*M //[]*M
	mux      sync.RWMutex
	//eventChan chan T
}

func (_this *EventBase[T, M]) Add(calback *M) {
	_this.mux.Lock()
	if _this.listener == nil {
		_this.listener = make(map[*M]*M)
	}
	_this.listener[calback] = calback
	_this.mux.Unlock()
}

func (_this *EventBase[T, M]) Remove(calback *M) {
	_this.mux.Lock()
	_, ok := _this.listener[calback]
	if ok {
		delete(_this.listener, calback)
	}
	_this.mux.Unlock()
}

func (_this *EventBase[T, M]) Clear() {
	_this.mux.Lock()
	_this.listener = nil
	_this.mux.Unlock()
}

func (_this *EventBase[T, M]) event(cal *func(*M)) {
	_this.mux.RLock()
	for _, v := range _this.listener {
		if v != nil {
			(*cal)(v)
		}
	}
	_this.mux.RUnlock()
}
